package org.example.platform.elasticsearch.service;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.example.platform.elasticsearch.entity.Hotel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsService {
    @Autowired
    private RestHighLevelClient client;

    public List<Hotel> getHotelFromTitle(String keyword) throws IOException {
        SearchRequest searchRequest = new SearchRequest("hotel"); //客户端请求
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建query
        searchSourceBuilder.query(QueryBuilders.matchQuery("title", keyword));
        searchRequest.source(searchSourceBuilder);
        ArrayList<Hotel> resultList = new ArrayList<>();
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        RestStatus status = searchResponse.status();
        if (status != RestStatus.OK) {
            return null;
        }
        SearchHits searchHits = searchResponse.getHits();
        for (SearchHit searchHit : searchHits) {
            Hotel hotel = new Hotel();
            hotel.setId(searchHit.getId());   //文档_id
            hotel.setIndex(searchHit.getIndex());   //索引名称
            hotel.setScore(searchHit.getScore());   //文档得分
            //转换为Map
            Map<String, Object> dataMap = searchHit.getSourceAsMap();
            hotel.setTitle((String) dataMap.get("title"));
            hotel.setCity((String) dataMap.get("city"));
            hotel.setPrice(Double.valueOf((String) dataMap.get("price")));
            resultList.add(hotel);
        }
        return resultList;
    }
}
